package com.geek.pokermanager.util;

import com.geek.pokermanager.model.RequestModel;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class HttpUtils {

    // 请求服务器端的url
    private static String server_base = ConfigTool.getString("Game.HostAddress");//换成域名 如：http://www.xxx.com/
    private static String path = "";//换成访问路径 如 index.php?m=app&c=app
    private static URL url;


    static {
        try {
            url = new URL(server_base+path);
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @param params
     *            填写的url的参数
     * @param encode
     *            字节编码
     * @return
     */
    public static String sendPostMessage(Map<String, String> params,
                                         String encode) {
        // 作为StringBuffer初始化的字符串
        StringBuffer buffer = new StringBuffer();
        try {
            if (params != null && !params.isEmpty()) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    // 完成转码操作
                    buffer.append(entry.getKey()).append("=").append(
                            URLEncoder.encode(entry.getValue(), encode))
                            .append("&");
                }
                buffer.deleteCharAt(buffer.length() - 1);
            }
            // System.out.println(buffer.toString());
            // 删除掉最有一个&

            //  System.out.println("-->>"+buffer.toString());
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();
            urlConnection.setConnectTimeout(3000);
            urlConnection.setRequestMethod("POST");
            urlConnection.setDoInput(true);// 表示从服务器获取数据
            urlConnection.setDoOutput(true);// 表示向服务器写数据
            // 获得上传信息的字节大小以及长度
            byte[] mydata = buffer.toString().getBytes();
            // 表示设置请求体的类型是文本类型
            urlConnection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");
            urlConnection.setRequestProperty("Content-Length",
                    String.valueOf(mydata.length));
            // 获得输出流,向服务器输出数据
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(mydata,0,mydata.length);
            outputStream.close();
            // 获得服务器响应的结果和状态码
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == 200) {
                return changeInputStream(urlConnection.getInputStream(), encode);
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            return "";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            //e.printStackTrace();
            return "";
        }
        return "";
    }

    /**
     * 将一个输入流转换成指定编码的字符串
     *
     * @param inputStream
     * @param encode
     * @return
     */
    public static String changeInputStream(InputStream inputStream,
                                            String encode) {
        // TODO Auto-generated method stub
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        String result = "";
        if (inputStream != null) {
            try {
                while ((len = inputStream.read(data)) != -1) {
                    outputStream.write(data, 0, len);
                }
                result = new String(outputStream.toByteArray(), encode);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String PostWithJson(String params) throws IOException {
 //         URL url = new URL(strURL);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Accept", "text/html"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            OutputStreamWriter out = new OutputStreamWriter(
                    connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.write(params);
            out.flush();
            out.close();
            // 读取响应
            int length = (int) connection.getContentLength();// 获取长度
            InputStream is = connection.getInputStream();
            if (length != -1) {
                byte[] data = new byte[length];
                byte[] temp = new byte[512];
                int readLen = 0;
                int destPos = 0;
                while ((readLen = is.read(temp)) > 0) {
                    System.arraycopy(temp, 0, data, destPos, readLen);
                    destPos += readLen;
                }
                String result = new String(data, "UTF-8"); // utf-8编码

                return result;
            }
        return "error"; // 自定义错误信息
    }

    public static void main(String[] agrs){
        List<String> args=new ArrayList<String>();
        RequestModel requestModel=new RequestModel();
        requestModel.setCmd("startPlug");
        String roomid="493716",user1Id = "1963",user2Id = "1964",user3Id = "1965",user4Id = "4444";
        int[] cards1={1,2,3,4,5,6,7,8,9,10,11,12,13};
        int[] cards2={14,15,16,17,18,19,20,21,22,23,24,25,26};
        int[] cards3={27,28,29,30,31,32,33,34,35,36,37,38,39};
        int[] cards4={40,41,42,43,44,45,46,47,48,49,50,51,52};
        args.add(roomid);
        args.add(user1Id);
        args.add(JacksonUtil.getJsonFromObject(cards1));
        args.add(user2Id);
        args.add(JacksonUtil.getJsonFromObject(cards2));
        args.add(user3Id);
        args.add(JacksonUtil.getJsonFromObject(cards3));
        args.add(user4Id);
        args.add(JacksonUtil.getJsonFromObject(cards4));
        requestModel.setArgs(args);
        String json = JacksonUtil.getJsonFromObject(requestModel);
        System.out.println(json);
        String result="";
		try {
			result = PostWithJson(json);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
        System.out.println(result);
        try {
            Thread.sleep(1000*10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
    private static void getUserId(){
    	List<String> args=new ArrayList<String>();
        RequestModel requestModel=new RequestModel();
        requestModel.setCmd("selectPlayer");
        args.add("1961");
        requestModel.setArgs(args);
        String json = JacksonUtil.getJsonFromObject(requestModel);
        System.out.println(json);
        String result = null;
		try {
			result = PostWithJson(json);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        System.out.println(result);
    }
}